//
//  AccountPassViewController.swift
//  TalkeTv
//
//  Created by lhf on 2024/9/19.
//

import UIKit
import Toast_Swift
import SwiftyJSON
import Alamofire

class AccountPassViewController: UIViewController,UITextFieldDelegate {
    
    @IBOutlet weak var userAccountTextField: UITextField!
    @IBOutlet weak var userPassTextField: UITextField!
    
    @IBOutlet weak var loginBtn: TDisableButton!
    var pageFrom = ""
    var qrcode = ""
    @IBOutlet weak var qrcodeTextField: UITextField!
    @IBOutlet weak var qrcodeBtn: UIButton!
    
    @IBAction func handleToScan(_ sender: Any) {
        let scan = ScanViewController.init()
        scan.modalPresentationStyle = .fullScreen
        scan.scanResBlock = { scanRes in
            self.qrcode = scanRes
            self.qrcodeTextField.text = scanRes
        }
        let nav = UINavigationController.init(rootViewController: scan)
        nav.modalPresentationStyle = .fullScreen
        
        self.present(nav, animated: true)
    }
    
    // MARK: - 登录
    @IBAction func goToLogin(_ sender: Any) {
        if userAccountTextField.text! == "" || !UtilManager.sharedInstance.is11Phone(text: userAccountTextField.text!) {
            self.view.makeToast("手机号码格式错误", duration: 1.0, position: .center)
            return
        }
        
        if userPassTextField.text == "" {
            self.view.makeToast("密码不能为空", duration: 1.0, position: .center)
            return
        }
        
        if (qrcodeTextField.text == "") {
            var params = JSON.init(parseJSON: "{}")
            params["username"].string = userAccountTextField.text
            params["password"].string = userPassTextField.text
            
            APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.login_action, method: HTTPMethod.post, params: params) { (result, error) in
                if error == nil {
                    var newData:[String:Any] = [:]
                    newData["token"] = result["data"].dictionaryObject?["token"]
                    newData["preUserAccount"] = self.userAccountTextField.text
                    UserInfo.sharedInstance.save(dic: newData)

                    self.handleGetUserInfo()
                }
            }
        } else {
            var params = JSON.init(parseJSON: "{}")
            params["username"].string = userAccountTextField.text
            params["password"].string = userPassTextField.text
            params["qrcode"].string = qrcodeTextField.text
            
            APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.account_tv_action, method: HTTPMethod.post, params: params) { (result, error) in
                if error == nil {
                    self.view.makeToast("登录成功", duration: 1.0, position: .center)
                    DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                        // TV一键登录 跳转到 账号密码登录
                        if self.qrcode != "" {
                            self.dismiss(animated: false, completion: nil)
                            TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
                            UserInfo.sharedInstance.toLogin("normal")
                        }
                    }
                }
            }
        }
    }
    
    // MARK: - 显示或隐藏密码
    @IBAction func hideOrShowPass(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        userPassTextField.isSecureTextEntry = !sender.isSelected
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        goToLogin(textField)
        return true
    }
    
    func handleGetUserInfo() {
        UtilManager.sharedInstance.showHud()
        
        let params = JSON.init(parseJSON: "{}")
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.user_info_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                UtilManager.sharedInstance.hideHud()
                
                var newData:[String:Any] = [:]
                newData["userId"] = result["data"].dictionaryObject?["userId"]
                newData["userAccount"] = result["data"]["accounts"]["attrs"].dictionaryObject?["mobile"]
                newData["userName"] = result["data"]["accounts"]["attrs"].dictionaryObject?["name"]
                newData["userAvatar"] = result["data"]["accounts"]["attrs"].dictionaryObject?["avatar"]
                UserInfo.sharedInstance.save(dic: newData)

                DispatchQueue.main.asyncAfter(deadline: .now()) {
                    self.dismiss(animated: true, completion: nil)
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
                }
                
                NotificationCenter.default.post(name: NSNotification.Name(AppConfig.sharedInstance.LoginNotification), object: self, userInfo: ["isLogin":UserInfo.sharedInstance.isLogin()])
            }
        }
    }
    
    @objc func userAccountTextChange() {
        checkLoginBtn()
    }
    
    @objc func userPassTextChange() {
        checkLoginBtn()
    }
    
    private func checkLoginBtn() {
        let isEnable = userAccountTextField.text!.count > 0 && userPassTextField.text!.count > 0
        loginBtn.changeDisableStatus(isEnable)
    }
    
    @objc func back(btn:UIButton)
    {
        self.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        userAccountTextField.text = UserInfo.sharedInstance.preUserAccount
        
//        userAccountTextField.text = "18150324376"
//        userPassTextField.text = "123456"
        
        userAccountTextChange()
        
        userAccountTextField.addTarget(self, action: #selector(userAccountTextChange), for: .editingChanged)
        userPassTextField.addTarget(self, action: #selector(userPassTextChange), for: .editingChanged)
        
        if qrcode != "" {
            qrcodeTextField.text = qrcode
        }
        
        if pageFrom == "atAuth" {
            // 返回按钮
            let leftBtn:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_left_black"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.back(btn:)))
            self.navigationItem.leftBarButtonItem = leftBtn
        }

        // Do any additional setup after loading the view.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
